from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

from Person.models import Person
from Problems.models import Problem


class Team(models.Model):
    name = models.CharField(max_length=128, unique=True)
    creator = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='team_creator')
    introduction = models.TextField(max_length=200, null=True, blank=True, verbose_name='团队简介')
    # 团队类型 公开 1，私有 0
    team_type = models.IntegerField(default=1, choices=((1, '公开'), (0, '私有')))
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now_add=True, verbose_name='更新时间')
    is_delete = models.BooleanField(default=False, verbose_name='删除标记')

    def __str__(self):
        return self.name

    @property
    def total_members(self):
        return self.team_detail.members.count()

    class Meta:
        ordering = ['id', '-create_time']


class TeamDetail(models.Model):
    team = models.OneToOneField(Team, on_delete=models.CASCADE, related_name='team_detail')

    avatar = models.ImageField(upload_to='TeamAvatar/', null=True, blank=True)

    # 团队成员
    members = models.ManyToManyField(Person, through='TeamMemberShip', related_name='teams', blank=True)

    # 团队公告
    announcement = models.TextField(null=True, blank=True, verbose_name='团队公告')

    def __str__(self):
        return self.team.name + "Detail"


class TeamMemberShip(models.Model):
    team = models.ForeignKey(TeamDetail, on_delete=models.CASCADE, related_name='team_member')
    person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='person_member')
    name = models.CharField(max_length=128, null=True, blank=True, verbose_name='成员备注')

    rating = models.IntegerField(default=1500)
    rank = models.IntegerField(default=0, null=True, blank=True, verbose_name='排名')

    is_active = models.BooleanField(default=False)  # 进入团队需要等待管理员审核，未通过状态为 False
    is_admin = models.BooleanField(default=False)  # 是否为团队管理员
    # 是否退出
    is_quit = models.BooleanField(default=False)  # 是否退出团队，包括审核被拒绝

    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now_add=True, verbose_name='更新时间')

    def __str__(self):
        return self.team.team.name + ": " + self.person.username


class TeamMemberRatingChange(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_rating_change')
    member = models.ForeignKey(TeamMemberShip, on_delete=models.CASCADE, related_name='rating_changes')
    change_rating = models.IntegerField(blank=False, null=False)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')


class TeamProblemList(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_problem_list')
    name = models.CharField(max_length=128, verbose_name='题单名称')
    problem_list = models.ManyToManyField(Problem, related_name='problem_list', blank=True)

    def __str__(self):
        return self.team.name


@receiver(post_save, sender=Team)
def create_team_detail(sender, instance, created, **kwargs):
    if created:
        # 创建 TeamDetail 实体
        team_detail = TeamDetail.objects.create(team=instance)
        # 将创建者加入 TeamMemberShip
        TeamMemberShip.objects.create(
            team=team_detail,
            person=instance.creator,
            rating=1500,
            is_active=True,
            is_admin=True
        )
